package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("EventpunishRestController")
public class EventpunishRestController extends CmiEmaController {

	/**
	 * Create a new Eventpunish entity
	 * 
	 */
	@RequestMapping(value = "/newEventpunish", method = RequestMethod.POST)
	@ResponseBody
	public Object newEventpunish(@RequestBody Eventpunish eventpunish) {
		eventpunishService.saveEventpunish(eventpunish);
		return JSONObject
				.parse(cmiPsonService.toJsonString(eventpunishDAO.findEventpunishByPrimaryKey(eventpunish.getId()), 2));
	}

	@RequestMapping(value = "/restNewEventpunish", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewEventpunish(@RequestBody String eventpunishJson) {
		Eventpunish eventpunish = new Gson().fromJson(eventpunishJson, Eventpunish.class);
		appendReferences(eventpunish);
		eventpunishService.saveEventpunish(eventpunish);
		return JSONObject
				.parse(cmiPsonService.toJsonString(eventpunishDAO.findEventpunishByPrimaryKey(eventpunish.getId()), 2));
	}

	@RequestMapping(value = "/saveEventpunish", method = RequestMethod.PUT)
	@ResponseBody
	public Eventpunish saveEventpunish(@RequestBody Eventpunish eventpunish) {
		eventpunishService.saveEventpunish(eventpunish);
		return eventpunishDAO.findEventpunishByPrimaryKey(eventpunish.getId());
	}

	@RequestMapping(value = "/restSaveEventpunish", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveEventpunish(@RequestBody String eventpunishJson) {
		Eventpunish eventpunish = new Gson().fromJson(eventpunishJson, Eventpunish.class);
		appendReferences(eventpunish);
		CmiPsonService cmiPsonService = new CmiPsonService();
		eventpunishService.saveEventpunish(eventpunish);
		return JSONObject
				.parse(cmiPsonService.toJsonString(eventpunishDAO.findEventpunishByPrimaryKey(eventpunish.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteEventpunish/{eventpunishId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteEventpunish(@PathVariable Integer eventpunishId) {
		Eventpunish eventpunish = eventpunishDAO.findEventpunishByPrimaryKey(eventpunishId);
		eventpunishService.deleteEventpunish(eventpunish);
	}

	@RequestMapping(value = "/restConfirmDeleteEventpunishs")
	@ResponseBody
	public Object restConfirmDeleteEventpunishs(@RequestBody Set<Integer> deleteEventpunishsIds) {
		Set<Eventpunish> deleteEventpunishs = eventpunishDAO.findEventpunishsByIds(deleteEventpunishsIds);
		Set<Eventpunish> referencedEventpunishs = eventpunishService.loadReferenceEventpunishs(deleteEventpunishs);
		deleteEventpunishs.removeAll(referencedEventpunishs);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedEventpunishs);
		jsonObject.put("deleteEntitys", deleteEventpunishs);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteEventpunishs")
	@ResponseBody
	public Object restDeleteEventpunishs(@RequestBody Set<Eventpunish> deleteEventpunishs) {
		Iterator<Eventpunish> iterator = deleteEventpunishs.iterator();
		while (iterator.hasNext()) {
			Eventpunish currentEventpunish = iterator.next();
			eventpunishService.deleteEventpunish(currentEventpunish);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listEventpunishs");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadEventpunish/{eventpunishId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventpunish(@PathVariable Integer eventpunishId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(eventpunishDAO.findEventpunishByPrimaryKey(eventpunishId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventpunishEvent/{eventpunishId}/event", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventpunishEvent(@PathVariable Integer eventpunishId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(eventpunishDAO.findEventpunishByPrimaryKey(eventpunishId).getEvent(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventpunishPunish/{eventpunishId}/punish", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventpunishPunish(@PathVariable Integer eventpunishId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(eventpunishDAO.findEventpunishByPrimaryKey(eventpunishId).getPunish(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	public void appendReferences(Eventpunish eventpunish) {

		Event event = eventpunish.getEvent();
		if (event != null)
			eventpunish.setEvent(eventService.findEventByPrimaryKey(event.getId()));

		Punish punish = eventpunish.getPunish();
		if (punish != null)
			eventpunish.setPunish(punishService.findPunishByPrimaryKey(punish.getId()));

	}

	@RequestMapping(value = "/restGetEventpunishEvent/{eventpunishId}/event", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventpunishEvent(@PathVariable Integer eventpunishId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(eventpunishDAO.findEventpunishByPrimaryKey(eventpunishId).getEvent(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventpunishPunish/{eventpunishId}/punish", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventpunishPunish(@PathVariable Integer eventpunishId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(eventpunishDAO.findEventpunishByPrimaryKey(eventpunishId).getPunish(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListEventpunishs", method = RequestMethod.GET)
	@ResponseBody
	public Object restListEventpunishs() {
		return JSONObject.parse(cmiPsonService.toJsonString(eventpunishService.loadEventpunishs(), 2));
	}

	@RequestMapping(value = "/restListEventpunishsPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListEventpunishsPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = eventpunishPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Eventpunish> eventpunishs = eventpunishDAO.findAllEventpunishs(startResult,
				cmiPagination.getPaginationSize());
		String eventpunishString = cmiPsonService.toPsonString(eventpunishs, 2, cmiPagination);

		return JSONObject.parse(eventpunishString);
	}

	@RequestMapping("/eventpunishSelectBox")
	@ResponseBody
	public JSONObject eventpunishSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Event":
				entitySet = eventService.loadEventsByIdSet(searchValue);
				break;
			case "Punish":
				entitySet = punishService.loadPunishsByIdSet(searchValue);
				break;

			// 被引用键
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Event":
				entitySet = eventDAO.findAllEvents((pageNumber - 1) * paginationSize, paginationSize);
				count = eventService.countEvents();
				break;
			case "Punish":
				entitySet = punishDAO.findAllPunishs((pageNumber - 1) * paginationSize, paginationSize);
				count = punishService.countPunishs();
				break;

			// 被引用键
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Event":
				entitySet = eventDAO.findEventByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = eventService.countEventsByName(queryword);
				break;
			case "Punish":
				entitySet = punishDAO.findPunishByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = punishService.countPunishsByName(queryword);
				break;

			// 被引用键
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
